package com.cs307.redcross.client;

import java.io.Serializable;


import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;

public class MyInfoContent extends Content implements Serializable {
	private static final long serialVersionUID = -1189011235559691201L;
	private DatabaseHandlerServiceAsync databaseHandlerService = (DatabaseHandlerServiceAsync) GWT.create(DatabaseHandlerService.class);
	private final String relogString = "If this problem persists try relogging into the system.";
	
	Person currentUser = Server.currentUser;
	
	Button editInfoButton;
	PopupPanel popup;
	AddPersonPopupPanel appp;
	LoadingPopupPanel lpp = new LoadingPopupPanel();
	ListBox cellCarrierCombobox;
	Label lblCellCarrier;
	TextBox cellPhoneNumberTextBox;
	Label lblCellPhone;
	TextBox emailTextBox;
	Label lblEmail;
	TextBox lastNameTextbox;
	Label lblLastName;
	TextBox firstNameTextbox;
	Label lblFirstName;
	Button saveInfoButton;
	Button cancelInfoButton;
	Label passwordLabel;
	Label retypePasswordLabel;
	PasswordTextBox passwordTextBox;
	PasswordTextBox retypePasswordTextbox;
	CheckBox changePasswordCheckbox;
	
	public MyInfoContent() {	
		
					
		AbsolutePanel absolutePanel = new AbsolutePanel();
		initWidget(absolutePanel);
		absolutePanel.setSize("592px", "647px");
		
		editInfoButton = new Button("Edit");
		editInfoButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				enableForm(false);
			}
		});
		absolutePanel.add(editInfoButton, 10, 485);
		editInfoButton.setSize("97px", "24px");
		
		cellCarrierCombobox = new ListBox();
		cellCarrierCombobox.addItem("AT&T");
		cellCarrierCombobox.addItem("Verizon");
		cellCarrierCombobox.addItem("T-Mobile");
		cellCarrierCombobox.addItem("Sprint PCS");
		cellCarrierCombobox.addItem("Virgin Mobile");
		cellCarrierCombobox.addItem("US Cellular");
		cellCarrierCombobox.addItem("Nextel");
		cellCarrierCombobox.addItem("Boost");
		cellCarrierCombobox.addItem("Alltel");
		absolutePanel.add(cellCarrierCombobox, 10, 280);
		cellCarrierCombobox.setSize("157px", "22px");
		
		lblCellCarrier = new Label("Cell Carrier:");
		absolutePanel.add(lblCellCarrier, 10, 256);
		lblCellCarrier.setSize("79px", "18px");
		
		cellPhoneNumberTextBox = new TextBox();
		cellPhoneNumberTextBox.setMaxLength(10);
		absolutePanel.add(cellPhoneNumberTextBox, 10, 225);
		cellPhoneNumberTextBox.setSize("150px", "14px");
		
		lblCellPhone = new Label("Cell Phone Number:");
		absolutePanel.add(lblCellPhone, 10, 201);
		lblCellPhone.setSize("119px", "18px");
		
		emailTextBox = new TextBox();
		absolutePanel.add(emailTextBox, 10, 153);
		emailTextBox.setSize("251px", "14px");
		
		lblEmail = new Label("Email:");
		absolutePanel.add(lblEmail, 10, 132);
		lblEmail.setSize("39px", "18px");
		
		lastNameTextbox = new TextBox();
		absolutePanel.add(lastNameTextbox, 10, 86);
		lastNameTextbox.setSize("251px", "14px");
		
		lblLastName = new Label("Last Name:");
		absolutePanel.add(lblLastName, 10, 62);
		lblLastName.setSize("79px", "18px");
		
		firstNameTextbox = new TextBox();
		firstNameTextbox.setFocus(true);
		absolutePanel.add(firstNameTextbox, 10, 34);
		firstNameTextbox.setSize("251px", "14px");
		
		lblFirstName = new Label("First Name:");
		absolutePanel.add(lblFirstName, 10, 10);
		lblFirstName.setSize("79px", "18px");
		
		saveInfoButton = new Button("Save");
		saveInfoButton.setText("Update");
		saveInfoButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if (firstNameTextbox.getText().replaceFirst(" ", "").equals("")) {
					Window.alert("A first name is needed.");
					return;
				}
				if (lastNameTextbox.getText().replaceFirst(" ", "").equals("")) {
					Window.alert("A last name is needed.");
					return;
				}
				if (emailTextBox.getText().replaceFirst(" ", "").equals("")) {
					Window.alert("An email is needed.");
					return;
				}
				if (!ValidatePhoneNumber(cellPhoneNumberTextBox.getText())) {
					Window.alert("An valid cell phone number is needed.");
					return;
				}
				if (cellPhoneNumberTextBox.getText().replaceFirst(" ", "").equals("")) {
					Window.alert("An cell phone is needed.");
					return;
				}
				
				if (changePasswordCheckbox.getValue()) {
					if (passwordTextBox.getText().replace(" ", "").equals("")) {
						Window.alert("Password field(s) cannot be blank.");
						return;
					}
					if (retypePasswordTextbox.getText().replace(" ", "").equals("")) {
						Window.alert("Password field(s) cannot be blank.");
						return;
					}
					if (!passwordTextBox.getText().equals(retypePasswordTextbox.getText())) {
						Window.alert("Passwords entered do not match each other.");
						return;
					}
				}
				
				currentUser.setFirstName(firstNameTextbox.getText()); 
				currentUser.setLastName(lastNameTextbox.getText());
				currentUser.setEmail(emailTextBox.getText());
				currentUser.setCarrier(cellCarrierCombobox.getItemText(cellCarrierCombobox.getSelectedIndex()));
				String pattern1 = "[^0-9]";
		    	String phoneNumber = cellPhoneNumberTextBox.getText().replaceAll(pattern1, "");
				currentUser.setCellPhoneNumber(phoneNumber);
				if( !passwordTextBox.getText().replaceFirst(" ", "").equals(""))
				{
					currentUser.setPassword(passwordTextBox.getText());
				}				
				if (currentUser instanceof Administrator) {
					databaseHandlerService.write((Administrator)currentUser, new AsyncCallback<Integer>() {
						
						@Override
						public void onSuccess(Integer result) {
							if (result > -1) {
								Window.alert("Your new info was successfully saved");
								disableForm();
							}
							else {
								Window.alert("Error: failed to update your info. " + relogString);
							}						
						}
						
						@Override
						public void onFailure(Throwable caught) {
							Window.alert("Error: failed to update your info. " + relogString);
						}
					});
				}
				else {
					databaseHandlerService.write((Volunteer)currentUser, new AsyncCallback<Integer>() {
						
						@Override
						public void onSuccess(Integer result) {
							if (result > -1) {
								Window.alert("The updates were succesfully saved.");
								disableForm();
							}
							else {
								Window.alert("Error: failed to update your info. " + relogString);
							}						
						}
						
						@Override
						public void onFailure(Throwable caught) {
							Window.alert("Error: failed to update your info. " + relogString + caught.toString());
						}
					});
				}
			}
		});
		absolutePanel.add(saveInfoButton, 10, 485);
		saveInfoButton.setSize("97px", "24px");
		
		cancelInfoButton = new Button("Save");
		cancelInfoButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				populateForm(currentUser);
				disableForm();
			}
		});
		cancelInfoButton.setText("Cancel");
		absolutePanel.add(cancelInfoButton, 113, 485);
		cancelInfoButton.setSize("97px", "24px");
		
		passwordLabel = new Label("New Password:");
		absolutePanel.add(passwordLabel, 10, 360);
		passwordLabel.setSize("157px", "18px");
		
		retypePasswordLabel = new Label("Retype New Password:");
		absolutePanel.add(retypePasswordLabel, 10, 411);
		retypePasswordLabel.setSize("185px", "18px");
		
		passwordTextBox = new PasswordTextBox();
		absolutePanel.add(passwordTextBox, 10, 384);
		passwordTextBox.setSize("177px", "13px");
		
		retypePasswordTextbox = new PasswordTextBox();
		absolutePanel.add(retypePasswordTextbox, 10, 435);
		retypePasswordTextbox.setSize("177px", "13px");
		
		changePasswordCheckbox = new CheckBox("Change password");
		changePasswordCheckbox.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
			public void onValueChange(ValueChangeEvent<Boolean> event) {
				if (changePasswordCheckbox.getValue()) {
					passwordLabel.setVisible(true);
					passwordTextBox.setVisible(true);
					retypePasswordLabel.setVisible(true);
					retypePasswordTextbox.setVisible(true);
				}
				else {
					passwordLabel.setVisible(false);
					passwordTextBox.setVisible(false);
					retypePasswordLabel.setVisible(false);
					retypePasswordTextbox.setVisible(false);
				}					
			}
		});
		absolutePanel.add(changePasswordCheckbox, 10, 335);
		
		populateForm(currentUser);
		disableForm();
		
		passwordLabel.setVisible(false);
		passwordTextBox.setVisible(false);
		retypePasswordLabel.setVisible(false);
		retypePasswordTextbox.setVisible(false);
	}
		
	private void populateForm(Person person) {
		if (person == null)
			return;
		
		firstNameTextbox.setText(person.getFirstName());
		lastNameTextbox.setText(person.getLastName());
		emailTextBox.setText(person.getEmail());
		cellPhoneNumberTextBox.setText(person.getCellPhoneNumber());
		for (int i = 0; i < cellCarrierCombobox.getItemCount(); i++) {
			if (cellCarrierCombobox.getItemText(i).equals(person.getCarrier())) {
				cellCarrierCombobox.setSelectedIndex(i);
				break;
			}
		}
	}
	
	private void disableForm() {

		saveInfoButton.setVisible(false);
		cancelInfoButton.setVisible(false);
		
		changePasswordCheckbox.setEnabled(false);
		firstNameTextbox.setEnabled(false);
		lastNameTextbox.setEnabled(false);
		emailTextBox.setEnabled(false);
		cellPhoneNumberTextBox.setEnabled(false);
		cellCarrierCombobox.setEnabled(false);
		editInfoButton.setEnabled(true);
		
		passwordLabel.setVisible(false);
		passwordTextBox.setVisible(false);
		retypePasswordLabel.setVisible(false);
		retypePasswordTextbox.setVisible(false);
		
		changePasswordCheckbox.setValue(false);
	}
	
	private void enableForm(boolean isAdmin) {
		changePasswordCheckbox.setEnabled(true);
		editInfoButton.setEnabled(false);
		saveInfoButton.setVisible(true);
		cancelInfoButton.setVisible(true);
		firstNameTextbox.setEnabled(true);
		lastNameTextbox.setEnabled(true);
		cellPhoneNumberTextBox.setEnabled(true);
		cellCarrierCombobox.setEnabled(true);
		passwordTextBox.setText("");
		retypePasswordTextbox.setText("");
	}
	
	//code from http://www.geekpedia.com/code35_Validate-phone-number-using-RegEx-and-Java.html
	public static boolean ValidatePhoneNumber(String phNumber)
    {
            boolean valResult = false;
            String numPattern = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$";
            valResult = phNumber.matches(numPattern);
            return valResult;
    }
}
